##############################################################################
#	Taho Jabber Bot ()
# 
#
#	This program is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 2 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
# 
#	Created  : december 2007
#
#	$Id: japrocs.tcl,v 0.0.0 2007/11/23 01:58:27
##############################################################################

set roster(users) ""
set pres(stat) "presence"
set pres(pri)  25
set pres(meta) "TahoJabberBot/$bot(version)"
set pres(show) "offline"
set pres(loc)  ""
set pres(x)    ""

set checkconn_sent 0
set checkconn_rcvd 0
set checkconn_tries 0



#### Функции работы с сервером


proc bot:connect {} {
global bot checkconn_sent checkconn_rcvd

  set bot(connected) 0
  set checkconn_sent 0
  set checkconn_rcvd 0

	if {[catch {set bot(socket) [socket $bot(host) $bot(port)]}] != 0} {
		putlog "ERROR: Невозможно соединиться с сервером\nвозможно отсутствует соединение с сетью интернет"
		return -1
	}
	if {[jlib::connect $bot(socket) $bot(host)] != 0} {
		return -2
	}
	jlib::send_auth $bot(userid) $bot(password) $bot(resource) "bot:login_cback"
	return 3
}


proc bot:login_cback {type data} {
global bot
  set bot(connected) 0

  if {$type == "OK"} {
    putlog "INFO: Авторизация на $bot(host) прошла успешно"

    #jlib::roster_get -command "client:roster"
    jlib::send_presence
    set bot(connected) 1

  } elseif {$type == "ERR"} {
    putlog "ERROR:  =FAILED>ОШИБКА"
  } elseif {$type == "DISCONNECT"} {
    putlog "ERROR: DISCONNECTED"
  }
}


proc bot:disconnect {type} {
global bot
  catch { jlib::disconnect }
  catch { unset bot(socket) }
  set bot(connected) 0
}

proc bot:reconnect {} {
  putlog "WARNING: переподключение"
  bot:disconnect "OK"
  #bot:connect
}

proc bot:checkconn_cback {type data} {
  global checkconn_rcvd

  if { $type == "ERR" } {
    bot:reconnect
  } else {
    set checkconn_rcvd 1
  }
}



proc bot:add_cback {type} {
global bot
	if {$type == "OK"} {
		putlog "INFO: callback добавлен"
	} else {
		putlog "ERROR: невозможно добавить callback"
	}
}


#### 


proc bot:checkinvite {} {
global bot invite_respondok
  set bot(inviteok) 1
  set invite_respondok [list]
}

proc bot:inviteok {hand idx text} {
global bot
  bot:checkinvite
}


####

proc bot:check {hand idx text} {
  bot:checkconn
}


proc bot:disco {hand idx text} {
  bot:disconnect "NOW"
}


####  Jabber Lib callbacks


proc client:iqreply {from useid id child} {
global tcl_platform
	putlog "Принят iq запрос от $from, UseID = $useid, ID = $id, содержимое = $child"
	if {$useid==1} {
		set out "<iq id='$id' to='$from' type='result' xml:lang='ru'><query xmlns='jabber:iq:version'><name>Tool Command Language</name><version>[info tclversion]</version><os>$tcl_platform(os) $tcl_platform(osVersion)</os></query></iq>"
	} else {
		set out "<iq to='$from' type='result' xml:lang='ru'><query xmlns='jabber:iq:version'><name>Tool Command Language</name><version>[info tclversion]</version><os>$tcl_platform(os) $tcl_platform(osVersion)</os></query></iq>"
	}

 jlib::outmsg $out
}

proc client:message {from type subject body extbody thread pri x} {
global bot

	if { $bot(inviteok) } {
		set jidindex -1
	} else {
		putlog "BOT NOT INVATED"
	}

	if { $x!="" } {
		parse_invite "$from" "$x"
	}

	if {$jidindex == -1} {
		if {$bot(say) == 1} {
			set text [string tolower $body ]
			bot:inmessage $from $type $body
		} else {
			putlog "Received Message from $from: $body"
		}
	} else {
		putlog "No answer"
	}
}



proc client:disconnect {} {
  ::LOG "We got disconnected"
  bot:reconnect
}


proc bot:splitjid {jid} {

  # разбиение адреса отправителя 

  set idx [string first / $jid]
  if {$idx == -1} {return [list $jid ""]}

  set user [string range $jid 0 [expr $idx - 1]]
  set res  [string range $jid [expr $idx + 1] end]

  return [list $user $res]
}




proc bot:msg {from type body} {
jlib::outmsg {<message to='$from' type='chat' xml:lang='ru'><body>$body</body></message>}
return $body
}

